import React from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import * as storeActionsFrom from '../../../actions/store.js'

import BuyAndStore from '../../../components/BuyAndStore'


// import './style.scss'

class Buy extends React.Component{
    constructor(props, context){
        super(props, context)
        this.state={
            isStore: false
        }
    }
    render() {
        return (
            <div>
                <BuyAndStore isStore={this.state.isStore} buyHandle={this.buyHandle.bind(this)} storeHandle={this.storeHandle.bind(this)}></BuyAndStore>
            </div>
        )
    }
    componentDidMount() {
        this.checkStoreState()
    }
    buyHandle() {
        const loginFlag = this.loginCheck()
        if(!loginFlag) {
            return
        }
        //购买的流程（省略）

        //跳转到用户主页
        this.props.history.push('/user')
    }

    storeHandle() {
        const loginFlag = this.loginCheck()
        if(!loginFlag) { //如果没有登录直接return
            return
        }

        const id = this.props.id
        const storeActions = this.props.storeActions

        if(this.state.isStore) {
            //已经收藏过了，点击时取消收藏
            storeActions.remove({id: id})
        } else {
            //没有被收藏，点击时收藏
            storeActions.add({id: id})
        }

        this.setState({
            isStore: !this.state.isStore
        })
    }

    checkStoreState() {
        const id = this.props.id
        const store = this.props.store
        store.some(item => {
            if(item.id === id) {
                this.setState({
                    isStore: true
                })
                //跳出循环
                return true
            }
        })
    }
    loginCheck() {
        //验证登录
        const id = this.props.id
        const userinfo = this.props.userinfo
        if(!userinfo.userName) {
            //跳转到登录页面
            this.props.history.push('/login/' + encodeURIComponent('/detail/' + id))
            return false
        } else {
            return true
        }
    }
}





function mapStateToProps(state) {
    return {
        userinfo: state.userinfo,
        store: state.store
    }
}

function mapDispatchToProps(dispatch){
    return {
        storeActions: bindActionCreators(storeActionsFrom, dispatch)
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Buy)